<?php
/**
 * Date: 13-6-17
 * 公用方法类
 */

namespace mphp\Common;


class Utils
{

    public static function isAjax()
    {
        if (!empty($_REQUEST['ajax'])
            ||!empty($_REQUEST['jsoncallback'])
            || (isset($_SERVER['HTTP_X_REQUESTED_WITH'])
                && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest')
        ) {
            return true;
        }
        return false;
    }


    /**
     * 过滤变量使输入的代码安全
     * @param $variable
     * @return string
     */
    static public function escape($variable,$strip_tags = false){
        if(is_array($variable)){
            foreach($variable as $key => $value){
                $variable[$key] = self::escape($value,$strip_tags);
            }
        }else{
            //HTML转义
            $variable = $strip_tags === true?strip_tags($variable):$variable;
            $variable = htmlspecialchars($variable, ENT_QUOTES, 'utf-8');
            //启用了magic_quotes
            if (!get_magic_quotes_gpc())
            {
                $variable = addslashes($variable);
            }
        }
        return $variable;
    }

    /**
     * 随机生成一个字符串
     * @param $length
     * @param $number
     * @param $not_o0
     * @return string
     */
    static function randString($length = 8, $number = true, $not_o0 = false)
    {
        $strings = 'ABCDEFGHIJKLOMNOPQRSTUVWXYZ';  //字符池
        $numbers = '0123456789';                    //数字池
        if ($not_o0)
        {
            $strings = str_replace('O', '', $strings);
            $numbers = str_replace('0', '', $numbers);
        }
        $pattern = $strings . $number;
        $max = strlen($pattern) - 1;
        $key = '';
        for ($i = 0; $i < $length; $i++)
        {
            $key .= $pattern{mt_rand(0, $max)};    //生成php随机数
        }
        return $key;
    }
}
